import styles from "./Index.module.less";
import { Button, Col, Form, Input, message, Modal, Row } from "antd";
import FontIcon from "@/components/public/fontIcon/Index";
import type { EmailLoginForm } from "@/types/login";
import { useEffect, useState } from "react";
import { emailLogin } from "@/api/modules/login";
import { getCode, sendEmail } from "@/api/modules/public";
import { useDispatch } from "react-redux";
import { setUserInfo } from "@/store/user/index";
import { useNavigate, useSearchParams } from "react-router-dom";
import type { SendEmailParams } from "@/types/email";
import { store } from "@/store";
import { getRoutesByRole } from "@/api/modules/menu";
import { setDynamicMenu } from "@/store/menu";

export default function Index() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [searchParams] = useSearchParams();
  const redirect = searchParams.get("redirect");
  // 登录信息
  const [form] = Form.useForm<EmailLoginForm>();

  const [btnText, setBtnText] = useState("获取验证码");

  // 登录处理函数
  const handleLogin = async () => {
    try {
      let data = form.getFieldsValue(true);
      const response = await emailLogin(data);

      // 登录成功
      const { access_token, refresh_token, userInfo } = response.data;
      localStorage.setItem("token", access_token);
      localStorage.setItem("refresh_token", refresh_token);
      dispatch(setUserInfo(userInfo));

      // 获取动态菜单
      const state = store.getState();
      let dynamicMenu = state.menu.dynamicMenu;
      const getRoutes = async () => {
        const res = await getRoutesByRole();
        dispatch(setDynamicMenu(res.data));
      };
      if (dynamicMenu.length === 0) {
        await getRoutes();
      }
      // 跳转
      navigate(redirect || "/");
    } catch (error) {
      handleeGetCode();
    }
  };

  const [codeUrl, setCodeUrl] = useState("");

  // 获取验证码
  const handleeGetCode = async () => {
    const res = await getCode();
    modalForm.setFieldsValue({
      code: "",
      codeKey: res.data.codeKey,
    });
    setCodeUrl(res.data.url);
  };

  // 验证邮箱rule
  const validateEmail = (__: any, value: any, callback: any) => {
    if (
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
        value
      )
    ) {
      callback();
    } else {
      callback(new Error("邮箱格式错误"));
    }
  };

  // 弹窗状态
  const [visible, setVisible] = useState(false);

  // 打开关闭
  const handleAfterOpen = (e: boolean) => {
    if (e) {
      handleeGetCode();
    }
  };

  const [modalForm] = Form.useForm<SendEmailParams>();

  const [time, setTime] = useState(120);
  let timer: any = null;
  // 确认回调

  const [messageApi] = message.useMessage();
  const handleOk = async () => {
    modalForm.validateFields().then(async () => {
      try {
        let data = modalForm.getFieldsValue(true);
        let res = await sendEmail(data);
        messageApi.success(res.message || "操作成功", 5);
        // 关闭验证码界面，并初始化状态
        setVisible(false);
        modalForm.setFieldsValue({
          codeKey: "",
          code: "",
        });
        form.setFieldValue("emailCode", "");

        // 接口调用成功后执行
        timer = setInterval(() => {
          setTime((tiem) => tiem - 1);
          setBtnText(time + "秒后重新获取");
          if (time <= 0) {
            clearInterval(timer.value);
            timer.value = undefined;
            setBtnText("获取验证码");
            setTime(120);
          }
        }, 1000);
      } catch (error) {
        handleeGetCode();
      }
    });
  };

  useEffect(() => {
    modalForm.setFieldsValue({
      type: "loginCode",
      email: "",
      codeKey: "",
      code: "",
    });
  }, []);

  return (
    <>
      <Form
        className={styles.form}
        form={form}
        name="login"
        layout="horizontal"
        autoComplete="off"
        onFinish={handleLogin}>
        <Form.Item
          name="email"
          rules={[{ required: true, message: "请输入邮箱" }, { validator: validateEmail }]}>
          <Input
            className={styles.input}
            size="large"
            placeholder="请输入邮箱"
            prefix={<FontIcon className={styles.icon} name="icon-email" />}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              modalForm.setFieldValue("email", e.currentTarget.value)
            }
          />
        </Form.Item>

        <Row gutter={8}>
          <Col span={16}>
            <Form.Item
              name="emailCode"
              rules={[
                { required: true, message: "请输入邮箱验证码" },
                { min: 6, max: 6, message: "验证码长度为 6 个字符" },
              ]}>
              <Input
                className={styles.input}
                size="large"
                placeholder="请输入邮箱验证码"
                prefix={<FontIcon className={styles.icon} name="icon-captcha" />}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Button
              className={styles.email_code}
              color="primary"
              variant="text"
              onClick={() => setVisible(true)}>
              {btnText}
            </Button>
          </Col>
        </Row>
        <Form.Item>
          <Button className={styles.submit} htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>

      <Modal
        title="验证码"
        centered
        open={visible}
        afterOpenChange={handleAfterOpen}
        forceRender
        onCancel={() => setVisible(false)}
        onOk={() => handleOk()}
        cancelText="取消"
        okText="确定">
        <Form
          className={styles.form}
          form={modalForm}
          name="modal"
          layout="horizontal"
          autoComplete="off"
          onFinish={handleLogin}>
          <Form.Item
            name="email"
            rules={[{ required: true, message: "请输入邮箱" }, { validator: validateEmail }]}>
            <Input
              className={styles.input}
              size="large"
              placeholder="请输入邮箱"
              prefix={<FontIcon className={styles.icon} name="icon-email" />}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                form.setFieldValue("email", e.currentTarget.value)
              }
            />
          </Form.Item>

          <Row gutter={8}>
            <Col span={16}>
              <Form.Item
                name="code"
                rules={[
                  { required: true, message: "请输入图形验证码" },
                  { min: 4, max: 4, message: "验证码长度为 4 个字符" },
                ]}>
                <Input
                  className={styles.input}
                  size="large"
                  placeholder="请输入图形验证码"
                  prefix={<FontIcon className={styles.icon} name="icon-captcha" />}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <img className={styles.code} src={codeUrl} onClick={handleeGetCode} />
            </Col>
          </Row>
        </Form>
      </Modal>
    </>
  );
}
